import { reactive, ref } from "vue";
import { allBaseList } from "../allBaseList";
//@ts-ignore
import type { StudentForm, StudentForm } from "@/types/student";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadFile,
} from "element-plus";
import { reqAddStu, reqUpdateStu } from "@/api/reqStu";
import router from "@/router";

const originStu: StudentForm = {
  name: "",
  gender: "",
  school: "",
  class: "",
  teacher_id: "",
  manager_id: "",
  grade: "",
  education: "",
  major: "",
  direction: "",
};
export const addStu = () => {
  const stuForm = ref<StudentForm>({ ...originStu });

  const stuFormEle = ref<FormInstance>();

  const reset = () => {
    stuForm.value = { ...originStu };
    stuFormEle.value?.resetFields();
  };

  const stuFormRules = reactive<FormRules<StudentForm>>({
    name: [
      { required: true, message: "请输入姓名", trigger: "blur" },
      { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
    ],
    gender: [{ required: true, message: "请选择性别", trigger: "change" }],
    school: [{ required: true, message: "请选择学校", trigger: "change" }],
    class: [{ required: true, message: "请选择班级", trigger: "change" }],
    teacher_id: [
      { required: true, message: "请选择辅导员", trigger: "change" },
    ],
    manager_id: [
      { required: true, message: "请选择班主任", trigger: "change" },
    ],
    grade: [{ required: true, message: "请选择年级", trigger: "change" }],
    education: [{ required: true, message: "请选择学历", trigger: "change" }],
    major: [{ required: true, message: "请选择专业", trigger: "change" }],
    direction: [{ required: true, message: "请选择方向", trigger: "change" }],
  });

  const submitStu = async () => {
    console.log("aaa");

    await stuFormEle.value?.validate();

    console.log("bbbb");

    const { status, data } = await reqAddStu(stuForm.value);

    console.log(status, data);
    if (status === 0) {
      ElMessage.success("添加成功");
      router.push({ name: "main" });
    } else {
      ElMessage.error("添加失败");
    }
  };

  const updateSTu = async () => {
    await stuFormEle.value?.validate();
    const { status } = await reqUpdateStu(stuForm.value);

    if (status === 0) {
      ElMessage.success("修改成功");
    }
  };

  const {
    directionList,
    tearchList,
    manageList,
    classList,
    gradeList,
    educationalLevelList,
    schoolList,
    majorList,
  } = allBaseList();

  return {
    stuForm,
    directionList,
    tearchList,
    manageList,
    classList,
    gradeList,
    educationalLevelList,
    schoolList,
    majorList,
    reset,
    stuFormRules,
    stuFormEle,
    submitStu,
    updateSTu
  };
};
